#!/usr/bin/env python26

import os
import socket
from subprocess import call

service_state = os.getenv('NAGIOS_SERVICESTATE')
service_state_type = os.getenv('NAGIOS_SERVICESTATETYPE')
service_description = os.getenv('NAGIOS_SERVICEDESC')
hostname = os.getenv('NAGIOS_HOSTNAME')
target_host = os.getenv('NAGIOS_HOSTADDRESS')
nrpe_exec = '/usr/local/nagios/libexec/check_nrpe'
nrpe_command = ''
skybot_server = ''
port = 7110
chat_name = "opsview"


def send_message(server_address, server_port, chat, message):
    '''
    Connect to the 'serveraddress' on 'serverport' and deliver our 'message' at the chat named 'chatname'
    '''
    # Construct the message the way SkyBot is expecting it.
    msg = "[" + chat + "][opsview] echo " + message
    # Create a socket. Connect. Send. Close.
    soc = socket.socket()
    try:
        soc.connect((server_address, port))
    except socket.error, err:
        print "Connection to %s on port %s failed: %s" % (server_address, server_port, err)
        return False
    soc.send(msg)
    soc.close()
    return True


if __name__ == '__main__':
    if service_state == 'CRITICAL' and service_state_type == 'HARD':
        try:
            call([nrpe_exec, "-H", target_host, "-c", nrpe_command], stderr=None, stdout=open('/dev/null', 'w'))
        except RuntimeError as err:
            print "Runtime error: ", err
        except:
            print "Unexpected error."
        else:
            notification = ("INFO: " + service_description + " on " + hostname + " has been restarted by Opsview")
            send_message(skybot_server, port, chat_name, notification)
